# -*- coding:utf-8 -*-

"""
=============================
this is a feibot product,
all rights reserved.
www.feibot.com
@author: Gu Tianyuan
@email: g@feibot.com
@time: 2023/5/22:14:54
@product: PyCharm
=============================
"""

import sys

from PyQt5.QtWidgets import QDialog, QApplication

sys.path.append('..')

from uiFiles import ui_activeSetting
from gtyConfig import language, configFileHandler, systemConfig
import uiTools
import time


class ActiveSetting(QDialog, ui_activeSetting.Ui_activeSettingDialog):

    def __init__(self, mainPage, eventQ, parent=None):
        super(ActiveSetting, self).__init__(parent)

        self.machineConfig = configFileHandler.UserConfigHandler()
        self.mmcConfig = configFileHandler.ConfigFileHandler(systemConfig.configFileEmmc)

        self.setupUi(self)
        uiTools.centerAndSetIcon(self)
        self.eventQ = eventQ
        self.mainPage = mainPage

        self.label_lowFreq1.setText(language.activeSetting_lowFreq1)
        self.label_lowFreq2.setText(language.activeSetting_lowFreq2)
        self.btn_lowFreqOn1.setText(language.activeSetting_lowFreqOn)
        self.btn_lowFreqOn2.setText(language.activeSetting_lowFreqOn)
        self.btn_lowFreqOff1.setText(language.activeSetting_lowFreqOff)
        self.btn_lowFreqOff2.setText(language.activeSetting_lowFreqOff)
        self.label_activePower.setText(language.activeSetting_activePower)
        self.btn_powerSet.setText(language.activeSetting_set)
        self.label_channel.setText(language.activeSetting_channel)
        self.btn_channelSet.setText(language.activeSetting_set)
        self.returnBtn.setText(language.activeSetting_back)
        self.rebootActiveBtn.setText(language.activeSetting_rebootActive)
        self.fanControlBtn_on.setText(language.operate_fanOn)
        self.fanControlBtn_off.setText(language.operate_fanOff)

        self.setWindowTitle('Active System')
        self.setGeometry(-200, -200, self.width(), self.height())

        # 连接
        self.btn_lowFreqOn1.clicked.connect(lambda: self.lowFreqControl(1, 'on', 0))
        self.btn_lowFreqOn2.clicked.connect(lambda: self.lowFreqControl(2, 'on', 0))

        self.btn_lowFreqOff1.clicked.connect(lambda: self.lowFreqControl(1, 'off', 0))
        self.btn_lowFreqOff2.clicked.connect(lambda: self.lowFreqControl(2, 'off', 0))

        self.btn_powerAdd.clicked.connect(lambda: self.lowFreqControl(0, 'power', '+'))
        self.btn_powerSubstruct.clicked.connect(lambda: self.lowFreqControl(0, 'power', '-'))
        self.btn_powerSet.clicked.connect(lambda: self.lowFreqControl(0, 'power', 'set'))

        self.btn_channelAdd.clicked.connect(lambda: self.lowFreqControl(0, 'channel', '+'))
        self.btn_channelSubstruct.clicked.connect(lambda: self.lowFreqControl(0, 'channel', '-'))
        self.btn_channelSet.clicked.connect(lambda: self.lowFreqControl(0, 'channel', 'set'))
        self.rebootActiveBtn.clicked.connect(lambda: self.lowFreqControl(0, 'rebootActive', 0))
        # 风扇控制
        self.fanControlBtn_on.clicked.connect(lambda: self.fanControl('on'))
        self.fanControlBtn_off.clicked.connect(lambda: self.fanControl('off'))

        # 收到心跳包
        self.mainPage.eventEngine.eventList['ui_getActiveHeartBeat'].connect(self.updateDisplay)

        # 内部变量
        self.lowFreqState = ['off', 'off', 'off']
        self.lowFreqPower = 50
        self.lowFreqCh = 0
        #实际功率用于映射功率 显示10%实际是40% 0%就是0，之后线性增加到100%
        self.lowFreqPower_act = 0

        # 上一次操作的秒
        self.lastActionTime = 0

    # 发生事件
    def sendEvent(self, task, eventName, eventData=None):
        if eventData is None:
            eventData = []
        e = [eventName, eventData]
        try:
            if task.upper() in self.eventQ.keys():
                self.eventQ[task.upper()].put(e)
        except Exception as e:
            print(e)

    # 开启关闭控制
    def lowFreqControl(self, ch, cmd, data):
        if cmd in ['on', 'off']:
            self.lowFreqState[ch] = cmd
            # 发送相关的串口指令
            if cmd == 'on':
                self.sendEvent("UART", 'uart_active_lfControl', [ch, 1])
            else:
                self.sendEvent("UART", 'uart_active_lfControl', [ch, 0])
            self.label_info.setText('set loop ' + str(ch) + ' ' + cmd)

        if cmd == 'power':
            if data == '+':
                if self.lowFreqPower + 10 <= 100:
                    self.lowFreqPower += 10
                    self.label_powerState.setText(str(self.lowFreqPower) + "%")
                    self.lastActionTime = time.time()
            if data == '-':
                if self.lowFreqPower - 10 >= 10:
                    self.lowFreqPower -= 10
                    self.label_powerState.setText(str(self.lowFreqPower) + "%")
                    self.lastActionTime = time.time()
            if data == 'set':
                self.label_info.setText('set loop power to ' + str(self.lowFreqPower) + '%')
                #映射功率 10%就是40%之后线性增加到100%
                if self.lowFreqPower == 0:
                    self.lowFreqPower_act = 0
                elif self.lowFreqPower >= 10:
                    self.lowFreqPower_act = 0.67 * self.lowFreqPower + 33.3
                    if self.lowFreqPower_act > 100:
                        self.lowFreqPower_act = 95
                self.sendEvent("UART", 'uart_active_lfPower', [1, round(self.lowFreqPower_act)])
                #self.sendEvent("UART", 'uart_active_lfPower', [1, round(self.lowFreqPower)])
        if cmd == 'channel':
            if data == '+':
                if self.lowFreqCh + 1 <= 5:
                    self.lowFreqCh += 1
                    self.label_lowFreqChannel.setText(str(self.lowFreqCh))
                    self.lastActionTime = time.time()
            if data == '-':
                if self.lowFreqCh - 1 >= 0:
                    self.lowFreqCh -= 1
                    self.label_lowFreqChannel.setText(str(self.lowFreqCh))
                    self.lastActionTime = time.time()
            if data == 'set':
                self.sendEvent("UART", 'uart_active_lfChannel', [1, self.lowFreqCh])
                self.label_info.setText('set loop channel to ' + str(self.lowFreqCh))

        if cmd == 'rebootActive':
            self.sendEvent('UART', 'uart_active_rebootReader', [])
            self.label_info.setText('active reader rebooted...')

    def updateDisplay(self, data):
        loop1 = '---'
        loop2 = '---'
        power = '---'
        channel = '---'
        states = ['off', 'on', 'break']
        try:
            loop1 = states[data[0]]
            self.lowFreqState[1] = loop1
            loop2 = states[data[1]]
            self.lowFreqState[2] = loop2
            if time.time() - self.lastActionTime > 5:
                power = str(data[4]) + '%'
                self.lowFreqPower = data[4]
                channel = str(data[5])
                self.lowFreqCh = data[5]
        except Exception as e:
            print(e)
        self.label_lowFreq1State.setText(loop1)
        self.label_lowFreq2State.setText(loop2)

        # 操作后5秒内不刷新显示
        if time.time() - self.lastActionTime > 5:
            self.label_powerState.setText(power)
            self.label_lowFreqChannel.setText(channel)

    # 风扇控制
    def fanControl(self, cmd):
        self.sendEvent('UART', 'uart_beep', 0.1)
        time.sleep(0.1)
        self.sendEvent('UART', 'uart_fanControl', cmd)
